﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using Chire.wechat;

namespace Chire.ChireInter.Exam
{
    /// <summary>
    /// Exam_Add 的摘要说明
    /// </summary>
    public class Exam_Add : IHttpHandler
    {
        HttpContext contextWithBase;
        string studentId = "";
        string examId = "";
        string linkId = "";
        string score = "";
        string fileUrl = "";
        string marks = "";

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            contextWithBase = context;
            analysisInfo();
        }

        #region 验证信息
        public void analysisInfo()
        {
            if (contextWithBase.Request.Form.AllKeys.Contains("studentId"))
            {
                studentId = contextWithBase.Request.Form["studentId"];
            }
            if (contextWithBase.Request.Form.AllKeys.Contains("examId"))
            {
                examId = contextWithBase.Request.Form["examId"];
            }
            if (contextWithBase.Request.Form.AllKeys.Contains("linkId"))
            {
                linkId = contextWithBase.Request.Form["linkId"];
            }
            if (contextWithBase.Request.Form.AllKeys.Contains("score"))
            {
                score = contextWithBase.Request.Form["score"];
            }
            if (contextWithBase.Request.Form.AllKeys.Contains("fileUrl"))
            {
                fileUrl = contextWithBase.Request.Form["fileUrl"];
            }
            if (contextWithBase.Request.Form.AllKeys.Contains("marks"))
            {
                marks = contextWithBase.Request.Form["marks"];
            }
            if (hasExam() == true)
            {
                updateExamInfo();
                insertImgList(linkId);
            }
            else {
                insertIntoDiary();
            }
        }
        #endregion

        #region 判断是否有内容
        public bool hasExam() { 
      
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string strselect = "select  * from exam where student_id = '"+studentId+"' and exam_id = '"+examId+"'";
            SqlCommand sqlcmd = new SqlCommand(strselect, sqlcon);
            SqlDataReader dr = sqlcmd.ExecuteReader();
            bool hasInfo = false;
            if (dr.Read())
            {
                hasInfo = true;
            }
            sqlcon.Close();
            return hasInfo;

        }
        #endregion

        #region 插入数据
        public void insertIntoDiary()
        {
            string linkId = Constance.Instance.getRandomStr(10);
          
            // 连接数据库
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();
            string StrInsert = "";
            StrInsert = "insert into exam(student_id,exam_id,score,linkId,datetime,marks) values(@student_id,@exam_id,@score,@linkId,@datetime,@marks)";
            SqlCommand cmd = new SqlCommand(StrInsert, sqlcon);
            // 添加参数并且设置参数值

            // 1. 作者id
            cmd.Parameters.Add("@student_id", SqlDbType.VarChar, 50);
            cmd.Parameters["@student_id"].Value = studentId;
            // 1. 日记标题
            cmd.Parameters.Add("@exam_id", SqlDbType.VarChar, 50);
            cmd.Parameters["@exam_id"].Value = examId;
            // 1. 日记标题
            cmd.Parameters.Add("@score", SqlDbType.VarChar, 50);
            cmd.Parameters["@score"].Value = score;
            // 1. 日记标题
            cmd.Parameters.Add("@linkId", SqlDbType.VarChar, 1000);
            cmd.Parameters["@linkId"].Value = linkId;
            // 2.日记详情
            cmd.Parameters.Add("@datetime", SqlDbType.VarChar, 1000);
            cmd.Parameters["@datetime"].Value = DateTime.Now.ToString(); ;
            // 2.日记详情
            cmd.Parameters.Add("@marks", SqlDbType.VarChar, 1000);
            cmd.Parameters["@marks"].Value = marks; ;
            
            // 执行插入数据的操作
            cmd.ExecuteNonQuery();
            sqlcon.Close();
            successManager();
        }
        #endregion

        #region 修改数据
        public void updateExamInfo() {
            //连接数据库
            SqlConnection sqlcon1 = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon1.Open();
            //修改数据信息
            string strSqls = "update exam set score = '" + score + "',datetime='" + DateTime.Now.ToString()+"' ,marks = '"+marks+"'  where student_id = '" + studentId + "' and exam_id ='" + examId + "' ";

            SqlCommand cmd = new SqlCommand(strSqls, sqlcon1);
            //添加参数并且设置参数值
            cmd.ExecuteNonQuery();
            sqlcon1.Close();
            successManager();
        }
        #endregion

        #region 成功方法
        public void successManager()
        {
            OutExam_Model out_base_setting = new OutExam_Model();
            out_base_setting.errCode = "200";
            out_base_setting.errMsg = "接口请求成功";
            out_base_setting.data = null;


            JsonSerializer serializer = new JsonSerializer();
            StringWriter sw = new StringWriter();
            serializer.Serialize(new JsonTextWriter(sw), out_base_setting);
            string info = sw.GetStringBuilder().ToString();
            contextWithBase.Response.Write(sw.GetStringBuilder().ToString());
        }
        #endregion

        #region 插入图片信息
        public void insertImgList(string linkId) {
            string[] workStringArr = fileUrl.Split(',');
            List<string> workList = workStringArr.ToList<string>();
            for (int i = 0; i < workList.Count; i++) { 
                string info = workList[i];
                addSubExam(info,linkId);
            }
        }
        #endregion

        // 1. 插入分页信息
        private void addSubExam(string title, string linkId)
        {
            // 连接数据库
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();
            string StrInsert = "";
            StrInsert = "insert into exam_sub(fileUrl,linkId) values(@fileUrl,@linkId)";
            SqlCommand cmd = new SqlCommand(StrInsert, sqlcon);
            // 添加参数并且设置参数值
            // 1. 作者id
            cmd.Parameters.Add("@fileUrl", SqlDbType.VarChar, 550);
            cmd.Parameters["@fileUrl"].Value = title;

            // 1. 作者id
            cmd.Parameters.Add("@linkId", SqlDbType.VarChar, 50);
            cmd.Parameters["@linkId"].Value = linkId;
            // 执行插入数据的操作
            cmd.ExecuteNonQuery();
            sqlcon.Close();
        }

        #region 其他
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        #endregion
       
    }
}